import { createRouter, createWebHistory } from 'vue-router'
import Login from '@/views/Login.vue'
import Register from '@/views/Register.vue'
import CustomerExchange from '@/views/CustomerExchange.vue'
import MerchantDashboard from '@/views/MerchantDashboard.vue'
import AdminLayout from '@/views/AdminLayout.vue'
import { useStore } from 'vuex'

const routes = [
  {
    path: '/',
    name: 'HomePage',
    component: () => import('@/views/Home.vue')
  },
  {
    path: '/login',
    name: 'LoginPage',
    component: Login
  },
  {
    path: '/register',
    name: 'Register',
    component: Register
  },
  {
    path: '/exchange',
    name: 'CustomerExchange',
    component: CustomerExchange
  },
  {
    path: '/merchant',
    name: 'MerchantDashboard',
    component: MerchantDashboard,
    meta: { requiresAuth: true, role: 'MERCHANT' },
    children: [
      {
        path: 'products',
        name: 'MerchantProducts',
        component: () => import('@/views/MerchantProducts.vue'),
        meta: { requiresAuth: true, role: 'MERCHANT' }
      },
      {
        path: 'codes',
        name: 'MerchantCodes',
        component: () => import('@/views/MerchantCodes.vue'),
        meta: { requiresAuth: true, role: 'MERCHANT' }
      },
      {
        path: 'orders',
        name: 'MerchantOrders',
        component: () => import('@/views/MerchantOrders.vue'),
        meta: { requiresAuth: true, role: 'MERCHANT' }
      },
      {
        path: 'delivery',
        name: 'MerchantDelivery',
        component: () => import('@/views/MerchantDelivery.vue'),
        meta: { requiresAuth: true, role: 'MERCHANT' }
      },
      {
        path: '',
        name: 'MerchantDefault',
        redirect: '/merchant'
      }
    ]
  },
  {
    path: '/admin',
    name: 'AdminLayout',
    component: AdminLayout,
    meta: { requiresAuth: true, role: 'admin' },
    children: [
      {
        path: 'dashboard',
        name: 'AdminDashboard',
        component: () => import('@/components/admin/Dashboard.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: 'merchants',
        name: 'MerchantManagement',
        component: () => import('@/components/admin/MerchantManagement.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: 'products',
        name: 'AdminProducts',
        component: () => import('@/components/admin/ProductManagement.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: 'exchange-codes',
        name: 'AdminExchangeCodes',
        component: () => import('@/components/admin/ExchangeCodeManagement.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: 'orders',
        name: 'AdminOrders',
        component: () => import('@/components/admin/OrderManagement.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: 'analytics',
        name: 'AdminAnalytics',
        component: () => import('@/components/admin/Analytics.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: 'settings',
        name: 'AdminSettings',
        component: () => import('@/components/admin/Settings.vue'),
        meta: { requiresAuth: true, role: 'ADMIN' }
      },
      {
        path: '',
        name: 'AdminDefault',
        redirect: '/admin/dashboard'
      }
    ]
  },
  {
    path: '/track/:orderNumber',
    name: 'OrderTracking',
    component: () => import('@/views/OrderTracking.vue')
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// Navigation guard
router.beforeEach((to, from, next) => {
  const store = useStore()
  const token = store.state.token
  const user = store.state.user
  const userRole = store.state.role
  const isAuthenticated = !!(token && user)

  // Prevent infinite redirects between the same paths
  if (to.path === from.path) {
    next();
    return;
  }

  // Check if this is immediately after login by checking if we're coming from login page
  const isAfterLogin = from.name === 'LoginPage' && to.name !== 'LoginPage';
  
  // Special handling for login route to prevent loops
  if (to.path === '/login' && isAuthenticated) {
    // If user is already logged in and trying to access login, redirect to dashboard
    if (userRole === 'ADMIN') {
      next('/admin/dashboard');
    } else if (userRole === 'MERCHANT') {
      next('/merchant');
    } else {
      next('/');
    }
    return;
  }

  // If the route requires authentication
  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isAuthenticated) {
      // Redirect to login page if not authenticated
      next({
        path: '/login',
        query: { redirect: to.fullPath }
      })
    } else {
      // For routes requiring auth, if we just logged in, 
      // allow navigation to proceed to give state time to update
      if (isAfterLogin) {
        next();
        return;
      }
      
      // Check user role if specified
      const requiredRole = to.meta.role
      if (requiredRole && userRole !== requiredRole) {
        // Redirect to appropriate dashboard based on user role
        if (userRole === 'ADMIN' && !to.path.startsWith('/admin')) {
          next('/admin/dashboard')  // Go to admin dashboard instead of generic admin route
        } else if (userRole === 'MERCHANT' && !to.path.startsWith('/merchant')) {
          next('/merchant')  // Go to merchant dashboard
        } else {
          // If user is already going to their appropriate route but role doesn't match,
          // redirect to default page to prevent loop
          next('/');
        }
      } else {
        next() // Proceed to the route
      }
    }
  } else {
    // Allow access to routes that don't require authentication
    next()
  }
})

export default router